﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Net.Http;

namespace CRUD
{
    public class DS_NET: IDS
    {
        public static HttpClient clientSocket = null;
        public static NetworkStream serverStream = default(NetworkStream);       
        string message = null;  
       
        void connect(string SendMSG)
        {
           

            string host = System.Net.Dns.GetHostName();
            int port = 13000;                               
            WebClient client = new WebClient();
            byte[] msg = Encoding.Default.GetBytes(SendMSG);           
            byte[] answer = client.UploadData("http://" + host + ":" + port + "/", msg);           
            message = Encoding.Default.GetString(answer);
            client.Dispose();            
        }        
        public override void Create(Person pp)
        {
            string strArray = "";
            strArray += pp.SaveToSCV();
            strArray += " ";
            string message = "Cr*" + path + "*" + strArray;
            connect(message);        
           
        }
        public override MyList Read()
        {
            MyList x = new MyList();
            string message = "R*" + path;
            connect(message);
            string[] split = message.Split(new Char[] { ' ' });
            foreach (string str in split)
            {
                if (str != "")
                {
                    string[] spliP = str.Split(new Char[] { ';' });
                    Person type = new Person();
                    type.LoadFromCSV(spliP);
                    x.Add(type);
                }
            }
            return x;
        }
        public override void Update(Person pp)
        {
            string message = "Up*" + path + "*" + pp.SaveToSCV();
            connect(message);
        }              
        public override IDS IsReady(string Fname)
        {

            path = Fname;
            IDS ret = null;
            string[] strArray = path.Split('*');
            string extension = strArray[0];
            if (extension == "NET")
            {
                ret = this;               
            }
            else
            {
                if (!(next == null)) ret = next.IsReady(Fname);
            }
            return ret;
        } 
        public override void Delete(int id)
        {
            string message = "Del*" + path +"*"+id.ToString();
            connect(message);
        }
    }
}
